package com.aaa.interceptor;

import com.aaa.util.JwtUtil;
import com.aaa.vo.Result;
import com.alibaba.fastjson.JSON;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @Description:
 * @author:LiWei
 * @date:2022年11月23日16:49
 */
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        //1.获取请求头种的token
        String token = request.getHeader("token");
        //2.判断token是否为null
        if(StringUtils.hasText(token)){
            //校验token是否合法
            if(JwtUtil.verifyToken(token)){
                return true;
            }
        }
        PrintWriter writer = response.getWriter();
        Result result=new Result(4001,"未登录");
        String jsonString = JSON.toJSONString(result);
        writer.print(jsonString);
        writer.flush();
        writer.close();
        return false;
    }
}
